<?php


namespace app\common\lib;


use app\common\business\Message;
use app\common\model\OverallConfig;
use app\common\model\PatientInfo;
use catchAdmin\visitPlan\model\VisitPlanDetail;
use think\facade\Log;

class PushMessage
{

    private static ?PushMessage $instance = null;

    public static function getInstance(): ?PushMessage
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
    }


    /**
     * @throws \JsonException
     */
    public function send(array $tubeData, string $pushType = 'ALL', int $delay = 0): bool
    {

        $result = false;

        switch (strtoupper($pushType)) {
            case "ALL":
            case "APP":
                $result = $this->sendMessage($tubeData);

                if ($result === false || $this->getTurn() === false) {
                    $result = $this->sendSmsMessage($tubeData, $delay);
                }
                break;
            case "SMS":
                $result = $this->sendSmsMessage($tubeData, $delay);
                break;
        }

        return $result;
    }

    private function sendMessage(array $data): bool
    {

        //todo 执行微信模板消息的推送
        try {
            foreach ($data["users"] as $k => $v) {

                (new Message())->saveMessage($data["type"], $data["business_id"], $data["task_name"], $v, $data["names"][$k] ?? "患者", $data["param"] ?? []);
                if (isset($data["source"]) && $data["source"] == "plan") {
                    $visitDetail = (new VisitPlanDetail())->field(["plan_list"])->where([["visit_id", "=", $data["business_id"]], ["patientId", "=", $v]])->find()->toArray();
                    if (!empty($visitDetail)) {
                        $index = count($visitDetail["plan_list"]) - 1;
                        $visitDetail["plan_list"][$index]["push_status"] = 1;
                        $visitDetail["plan_list"][$index]["push_date"] = date("Y-m-d H:i:s");
                        $result = ZhyxMongo::getInstance()->setCollection('visit_plan_detail')->updateOne(
                            ["visit_id" => $data['business_id'], 'patientId' => $v],
                            ['$set' => [
                                'plan_list' => $visitDetail["plan_list"]
                            ]]
                        );
                    }
                }
            }
        } catch (\Exception $exception) {

            Log::error("更新状态异常:" . $exception->getMessage());
        }

        return true;


    }

    /**
     * @throws \JsonException
     */
    private function sendSmsMessage(array $data, int $delay = 0): bool
    {

        $result = ZhyxBeanstalkd::getInstance()->beansTalk->useTube("sendSms")->put(json_encode($data, JSON_THROW_ON_ERROR), 0, $delay);

        if ($result->getId()) {
            return true;
        }
        return false;

    }

    private function getTurn(): bool
    {
        $turnInfo = (new OverallConfig())->where([["flag", "=", 'sfyxjts']])->find();

        return $turnInfo ? (bool)$turnInfo["status"] : false;
    }
}